<!--  -->
<template>
  <div>
    <el-switch  v-model="draggable"  active-text="开启拖拽"  inactive-text="关闭拖拽"></el-switch> 
    <el-button v-if="draggable" @click="batchSave">批量保存</el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
    <el-tree
      :data="menusData"
      :props="defaultProps"
      :expand-on-click-node="false"
      show-checkbox
      node-key="catId"
      :default-expanded-keys="expendedKey"
      :draggable="draggable"  
      :allow-drop="allowDrop"
      :allow-drag="allowDrag"
      @node-drop="handleDrop"
      ref="menuTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            Append
          </el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
          <el-button type="text" size="mini" @click="() => edit(data)">
            Edit
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <!-- dialogVisible为true时(append方法被触发)，显示对话框 -->
      <el-form :model="category">
        <el-form-item label="类别名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <el-form :model="category">
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <el-form :model="category">
        <el-form-item label="计量单位">
          <el-input
            v-model="category.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框的两个按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <!-- 点击确定后，触发submitData方法，提交数据到后台服务器 -->
        <el-button type="primary" @click="submitData()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { Tree } from 'element-ui'

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},

  data() {
    //这里存放数据
    return {
      draggable: false, // 默认关闭拖拽功能
      pCid: [],    // 刷新页面后需展开的父节点
      maxLevel: 1, // 节点的最大深度,需指定默认值！
      updateNodes: [], // 完成拖拽后需更新数据的节点列表
      dialogType: "", // append,edit
      title: "",
      menusData: [],
      expendedKey: [],
      dialogVisible: false,
      category: {
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        catId: null,
        icon: "",
        productUnit: "",
      },
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},

  //方法集合
  methods: {
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        console.log("成功获取数据", data.data);
        this.menusData = data.data;
      });
    },

    batchDelete(){
      console.log("=======================");
      let todeleteNode = [];
      let todeleteNodeName = [];

      let checkedNodes = this.$refs.menuTree.getCheckedNodes();
      console.log(checkedNodes);
      for (let i = 0; i < checkedNodes.length; i++) {
        todeleteNode.push(checkedNodes[i].catId);
        todeleteNodeName.push(checkedNodes[i].name);        
      }
      
      // 删除前弹框确认
      this.$confirm(`是否删除【${todeleteNodeName}】菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(todeleteNode, false),
          }).then(({ data }) => {
            // 显示删除成功的消息并刷新界面
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getMenus(); // 刷新数据
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // ================= 批量保存之前的所有拖拽操作造成的修改 =================
    batchSave(){
      this.$http({
        url: this.$http.adornUrl('/product/category/update/sort'),
        method: 'post',
        data: this.$http.adornData(this.updateNodes, false)
      }).then(({ data }) => {
        this.$message({
              type: "success",
              message: "菜单修改成功!",
        });

        this.getMenus(); // 刷新数据
        console.log("需展开节点id：", this.pCid)
        this.expendedKey = this.pCid; // 
        
        this.maxLevel = 1;   // 操作完成后将属性重置为默认值！！
        this.updateNodes = []; 
      });
    },

    allowDrag(draggingNode) {
      return true; // 所有节点均允许拖拽
    },

    // ================= 判断被拖拽的节点是否可以被放置在此处 =================
    allowDrop(draggingNode, dropNode, type) {
      console.log(draggingNode.data.name, dropNode.data.name, type);
      this.maxLevel = 1;  // 指定初始值，避免批量保存时被其他拖拽操作污染数据
      this.countNodeLevel(draggingNode);  // 计算被拖拽节点的最大深度

      // 按照当前被拖拽节点所处的树 最新的数据，而非数据库里面的数据，计算被拖拽节点的总层数
      let draggingNodeDeep = Math.abs(this.maxLevel - draggingNode.level) + 1;   // 节点的最大深度 - 节点当前所在层级 + 1
      console.log("被拖拽节点的总层数：" + draggingNodeDeep);

      if (type == "inner") {  // 拖到节点里面
        return draggingNodeDeep + dropNode.level <= 3;
      } else {   // 前后位置移动
        return draggingNodeDeep + dropNode.parent.level <= 3;
      }
    },
    countNodeLevel(node) {
      // 批量保存场景下，节点在数据库中子节点数据node.children.data可能与当前状态不一致，需使用最新状态node.childNodes
      if (node.childNodes && node.childNodes.length > 0) {   
        for (let i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[i].level > this.maxLevel) {
            this.maxLevel = node.childNodes[i].level;
          }
          this.countNodeLevel(node.childNodes[i]);
        }
      }
    },

    // ================= 节点被拖拽成功时，触发的事件 =================
    // 被拖拽节点对应的 Node、结束拖拽时最后进入的节点、被拖拽节点的放置位置（before、after、inner）、event
    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log("当前拖拽情况: ", draggingNode, dropNode, dropType);
      let pCid = 0; // 被拖拽节点的最新父节点id
      let siblings = null; // 被拖拽节点 的最新兄弟姐妹节点

      if (dropType == "inner") {
        pCid = dropNode.catId;
        siblings = dropNode.childNodes;
      } else if (dropType == "before" || dropType == "after") {
        pCid = dropNode.parent.data.catId == undefined ? 0 : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes;
      }
      this.pCid.push(pCid);
      console.log("当前父节点id：", pCid, "，被拖拽节点本级节点全家福：", siblings);

      for (let i = 0; i < siblings.length; i++) {
        // 更新节点的排序
        if (siblings[i].data.catId == draggingNode.data.catId) {
          console.log("====在本级节点全家福中，发现当前被拖拽的节点====");
          let catLevel = draggingNode.level;
          if (siblings[i].level != catLevel) {
            console.log("========当前被拖拽的节点 发生了层级变化，需更新被拖拽节点及其子节点的层级========");
            catLevel = siblings[i].level; 
            this.updateChildNodesLevel(siblings[i]); 
          }
          this.updateNodes.push({catId: siblings[i].data.catId,  sort: i,
                                parentCid: pCid, catLevel: catLevel,    // 更新所在层级和父节点id
          }); 
        } else {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
        }
      }
      console.log("需更新的节点数据：", this.updateNodes);
    },
    updateChildNodesLevel(node) {
      for (let i = 0; i < node.childNodes.length; i++) {
        this.updateNodes.push({
          catId: node.childNodes[i].data.catId,
          catLevel: node.childNodes[i].level,
        });
        this.updateChildNodesLevel(node.childNodes[i]);
      }
    },

    append(data) {
      console.log("append", data);
      this.dialogVisible = true;
      this.dialogType = "append";
      this.title = "添加分类";

      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1; // 避免是字符串形式

      this.category.name = "";
      this.category.catId = null;
      this.category.icon = "";
      this.category.productUnit = "";
    },

    remove(node, data) {
      console.log("append", node, data);
      var ids = [data.catId];
      // 删除前弹框确认
      this.$confirm(`是否删除【${data.name}】菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            // 显示删除成功的消息并刷新界面
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getMenus(); // 刷新数据
            this.expendedKey = [node.parent.data.catId];
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    edit(data) {
      console.log("要修改的数据为：", data);
      this.dialogVisible = true;
      this.dialogType = "edit";
      this.title = "修改分类";

      // 发送请求，获取当前节点最新数据以渲染页面
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
      }).then(({ data }) => {
        this.category.name = data.data.name;
        this.category.catId = data.data.catId;
        this.category.icon = data.data.icon;
        this.category.productUnit = data.data.productUnit;
        this.category.parentCid = data.data.parentCid;
      });
    },

    submitData() {
      if (this.dialogType == "append") {
        // 将要添加的类别信息，发送给后台服务器
        console.log("要添加的类别信息为：", this.category);
        this.$http({
          url: this.$http.adornUrl("/product/category/save"),
          method: "post",
          data: this.$http.adornData(this.category, false),
        }).then(({ data }) => {
          console.log("后台返回：", data);
          this.$message({
            type: "success",
            message: "数据提交成功!",
          });
          this.dialogVisible = false; // 关闭对话框
          this.getMenus(); // 刷新数据
          this.expendedKey = [this.category.parentCid]; // 展开相应的菜单
        });
      } else if (this.dialogType == "edit") {
        // 将要更新的类别信息，发送给后台服务器
        var { catId, name, icon, productUnit } = this.category; // 解构对象,避免直接使用this.category时一些属性被设置为默认值
        this.$http({
          url: this.$http.adornUrl("/product/category/update"),
          method: "post",
          data: this.$http.adornData({ catId, name, icon, productUnit }, false),
        }).then(({ data }) => {
          console.log("后台返回：", data);
          if (data.code == 0) {
            this.$message({
              type: "success",
              message: "数据提交成功!",
            });
            this.dialogVisible = false; // 关闭对话框
            this.getMenus(); // 刷新数据
            this.expendedKey = [this.category.parentCid]; // 展开相应的菜单
          }
        });
      }
    },

    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
  },

  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getMenus();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
};
</script>

<style lang='scss' scoped>
//@import url(); 引入公共css类
</style>